﻿#region Copyright 
/*-------------------------------------------------------------------------
* 命名空间名称/文件名:    SSPivot.Common.Helpers/ServerRequestHelper 
* CLR版本:     4.0.30319.42000
* 机器名称:    DESKTOP-NHMLO8A
* 功 能：       N/A
* 类 名：       ServerRequestHelper
* 创建时间：  2025/6/4 15:55:45
* 版本号：      v1.0
* 创建人:        xulong
*-------------------------------------------------------------------------*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SSPivot.Common.Helpers
{
    /// <summary>
    /// Request操作类
    /// </summary>
    public class ServerRequestHelper
    {
        /// <summary>
        /// 判断当前页面是否接收到了Post请求
        /// </summary>
        /// <returns>是否接收到了Post请求</returns>
        public static bool IsPost()
        {
            return AppContextProvider.Current.HttpContext.Request.Method.ToUpper().Equals("POST");
        }
        /// <summary>
        /// 判断当前页面是否接收到了Get请求
        /// </summary>
        /// <returns>是否接收到了Get请求</returns>
        public static bool IsGet()
        {
            return AppContextProvider.Current.HttpContext.Request.QueryString.HasValue;

        }

        /// <summary>
        /// 返回上一个页面的地址
        /// </summary>
        /// <returns>上一个页面的地址</returns>
        public static string GetUrlReferrer()
        {
            return AppContextProvider.Current.HttpContext.Request.Headers["Referer"];

        }

        /// <summary>
        /// 得到当前完整主机头
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentFullHost()
        {
            return AppContextProvider.Current.HttpContext.Request.Host.ToString();

        }

        /// <summary>
        /// 获取当前站点完整的HTTP路径
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentFullHTTPHost()
        {
            return string.Format("{0}://{1}", AppContextProvider.Current.HttpContext.Request.Scheme, GetCurrentFullHost());

        }

        /// <summary>
        /// 得到主机头
        /// </summary>
        /// <returns></returns>
        public static string GetHost()
        {
            return AppContextProvider.Current.HttpContext.Request.Host.ToString();

        }


        /// <summary>
        /// 获取当前请求的原始 URL(URL 中域信息之后的部分,包括查询字符串(如果存在))
        /// </summary>
        /// <returns>原始 URL</returns>
        public static string GetRawUrl()
        {
            return string.Format("{0}{1}", AppContextProvider.Current.HttpContext.Request.Path, AppContextProvider.Current.HttpContext.Request.QueryString);

        }

        /// <summary>
		/// 获取页面地址（不带参数）
		/// </summary>
		/// <returns>URL</returns>
		public static string GetPathUrl()
        {
            return AppContextProvider.Current.HttpContext.Request.Path;

        }

        /// <summary>
		/// 获取当前请求的URL（绝对地址）
		/// </summary>
		/// <returns>URL</returns>
		public static string GetAbsoluteUrl()
        {
            return $"{AppContextProvider.Current.HttpContext.Request.Host}/{AppContextProvider.Current.HttpContext.Request.Path}";

        }

        /// <summary>
        /// 判断当前访问是否来自浏览器软件
        /// </summary>
        /// <returns>当前访问是否来自浏览器软件</returns>
        public static bool IsBrowserGet()
        {
            List<string> browserName = new List<string>() { "ie", "opera", "netscape", "mozilla", "konqueror", "firefox" };

            string curBrowser = AppContextProvider.Current.HttpContext.Request.Headers["User-Agent"].FirstOrDefault();

            return browserName.Any(e => curBrowser.Contains(e));
        }

        /// <summary>
        /// 判断是否来自搜索引擎链接
        /// </summary>
        /// <returns>是否来自搜索引擎链接</returns>
        public static bool IsSearchEnginesGet()
        {
            if (string.IsNullOrEmpty(AppContextProvider.Current.HttpContext.Request.Headers["Referer"].FirstOrDefault())) return false;

            List<string> SearchEngine = new List<string>() { "google", "yahoo", "msn", "baidu", "sogou", "sohu", "sina", "163", "lycos", "tom", "yisou", "iask", "soso", "gougou", "zhongsou" };

            string curReferrer = AppContextProvider.Current.HttpContext.Request.Headers["Referer"].ToString().ToLower();

            return SearchEngine.ToList().Any(e => curReferrer.Contains(e));
        }

        /// <summary>
        /// 获得当前页面的名称
        /// </summary>
        /// <returns>当前页面的名称</returns>
        public static string GetPageName()
        {
            string[] urlArr = AppContextProvider.Current.HttpContext.Request.Path.ToString().Split('/');

            return urlArr[urlArr.Length - 1].ToLower();
        }

        /// <summary>
        /// 返回表单或Url参数的总个数
        /// </summary>
        /// <returns></returns>
        public static int GetParamCount()
        {
            return AppContextProvider.Current.HttpContext.Request.Form.Count + AppContextProvider.Current.HttpContext.Request.Query.Count;

        }

        /// <summary>
        /// 获取服务器IP
        /// </summary>
        /// <returns></returns>
        public static string GetServerIP()
        {
            return AppContextProvider.Current.HttpContext.Connection.LocalIpAddress?.ToString();

        }

        /// <summary>
        /// 获得当前页面客户端的IP
        /// </summary>
        /// <returns>当前页面客户端的IP</returns>
        public static string GetRemoteIP()
        {
            var ip = AppContextProvider.Current.HttpContext?.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ip)) ip = AppContextProvider.Current.HttpContext?.Connection.RemoteIpAddress?.ToString() ?? string.Empty;
            return ip;

        }

        /// <summary>
        /// 判断当前页面是不是经过本站的链接进入的
        /// </summary>
        public static bool IsCurrentHostReferrer()
        {
            if (GetUrlReferrer().IndexOf(ServerRequestHelper.GetHost()) < 0)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 获取路径的物理地址
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string GetMapPath(string path)
        {
            if (AppContextProvider.Current.HttpContext != null)
            {
                //var host = AppDependencyResolver.Current.GetService<IWebHostEnvironment>();
                //return System.IO.Path.Combine(AppContextProvider.Current.WebHostEnvironment.ContentRootPath, StringHelper.TrimString(StringHelper.TrimString(FormatMapPath(path), @"\"),"~"));
                //return string.Format("{0}{1}", AppContextProvider.Current.HostingEnvironment.ContentRootPath, FormatMapPath(path));
                return null;
            }
            else
            {
                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
            }

        }


        public static string GetWebRootPath(string path)
        {
            if (AppContextProvider.Current.HttpContext != null)
            {
                //return System.IO.Path.Combine(AppContextProvider.Current.WebHostEnvironment.WebRootPath, StringHelper.TrimString(StringHelper.TrimString(FormatMapPath(path), @"\"), "~"));
                return null;
            }
            else
            {
                return path;
            }
        }

        /// <summary>
        /// 格式化绝对地址
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string FormatMapPath(string path)
        {
            if (string.IsNullOrEmpty(path)) return string.Empty;
            return path.Replace("/", "\\");
        }

        /// <summary>
        /// 判断当前URL是否是本地测试地址
        /// </summary>
        /// <returns></returns>
        public static bool IsLocalHostTransport()
        {
            return (ServerRequestHelper.GetHost().Equals("localhost") || ServerRequestHelper.GetHost().Equals("127.0.0.1"));
        }
    }
}
